package com.fyzk.activity.zhifu;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.lottery.jc.football.guoguan.JC_GuoGuanDialog;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderActivity;
import com.fyzk.activity.lottery.togetherbuy.HeMaiFaQiActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.coupon.CouponZhifuView;
import com.fyzk.activity.user.xiangxi.JCOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.NumLotteryOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.OldFootballOrderDetailActivity;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.BetResponse;
import com.fyzk.bean.CouponListBean;
import com.fyzk.bean.CouponListByLotteryBean;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.fyzk.dialog.SureDialog;
import com.fyzk.dialog.SureDialog.OnDialogOKCancleClickListener;
import com.fyzk.model.UMengTongJi_eventIds;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.L;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * 支付基类
 *
 * @author mm
 */
public abstract class BetBaseActivity extends BaseActivity implements
        OnClickListener, CouponZhifuView.OnCheckCouponListener {

    public int lotteryId;

    private RelativeLayout zhifu_top_rl;

    protected TextView top_title;
    protected TextView top_hemai;
    protected TextView po_instruction;

    private ImageView top_back;
    protected LinearLayout center_ll;
    public TextView btm_zhu;
    public TextView btm_bei;
    public TextView btm_money;
    public TextView btm_leftMoney;
    public TextView btm_sure;
    public TextView btm_clear;
    public TextView btm_bask;//发起晒单

    public int beishu = 1;
    protected int zhuiQi = 1;
    protected int zhuiQi_GaoJi = 1;
    protected boolean isPrizeStop = false;
    protected String phases = "";
    protected String beiShus = "";

    protected boolean isGaoJiZhuiHao;

    protected boolean isZhuijia = false;
    protected int changCi = 0;
    /**
     * 清除对话框
     */
    private SureDialog clearDialog = null;
    /**
     * 是否支付对话框
     */
    private AlertDialog payDialog = null;
    /**
     * 时间截止提示对话框
     */
    public SureDialog endTimeDialog = null;

    protected int zhushu = 0;

    protected CouponZhifuView couponZhifuView;
    protected long couponMoney = 0;
    protected String couponId = "";

    // 最小合买彩金
    private final int MIN_HEMAI = 20;
    // 最小投注彩金
    private final int MIN_TOUZHU = 20;

    protected int recommendType = 0;    // 晒单方式 0推荐、1不推荐、2保密
    protected int proportionType = 1;//1奖金分成，2利润分成，3投注彩金分成
    protected int proportions = -1;//佣金百分比
    protected int isShowAmt = 0;//是否显示购买金额：0显示；1不显示
    protected int isShowMaxSP = 0;//是否显示此单最高赔率---0显示---1不显示

    protected double minPrize = 0;  // 最小奖金
    protected double maxBounusPrize = 0;  // 最大奖金
    protected boolean isDanguan;//竞彩足球过关方式
    protected String expectedPrize = ""; // 预计奖金

    private String orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zhifu);
        JC_GuoGuanDialog.result = "2串1";
        lotteryId = getIntent().getIntExtra(IntentParamUtils.LOTTERYID, 0);
        isDanguan = getIntent().getBooleanExtra(IntentParamUtils.TYPE_GUOGUAN, false);
        initView();
        couponZhifuView = new CouponZhifuView(this, this);
        addCenter();
        setTitleStr();

        mImmersionBar.getTag(TAG)
                .statusBarColor(R.color.top_bg)
                .autoDarkModeEnable(true)
                .addTag(TAG)
                .init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MySharedPreferences.getInstance().getLoginStatus()) {
            DJ_ProgressDialog.show(getContext(), true, true);
            findUserAccount();
            getCoupon();
        } else {
            couponZhifuView.setList(new ArrayList<CouponListBean.CouponsBean>());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == IntentParamUtils.ZHIFU_RESULT) {
            AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
            clear();
            finish();
        } else if (resultCode == IntentParamUtils.LOWMONEY_TO_RECHARGE_OK) {
            buyOk(orderId, "投注成功");
        } else if (resultCode == IntentParamUtils.LOWMONEY_TO_RECHARGE_FAIL) {
            buyOk(orderId, "订单等待支付");
        }
        if (requestCode == IntentParamUtils.JC_GENDAN) {
            if (resultCode == IntentParamUtils.OK) {
                recommendType = data.getIntExtra("recommendType", -1);
                proportions = data.getIntExtra("proportions", -1);
                proportionType = data.getIntExtra("proportionType", -1);
                isShowAmt = data.getIntExtra("isShowAmt", -1);
                isShowMaxSP = data.getIntExtra("isShowMaxSP", -1);
            }
        }
    }

    @Override
    public void onBackPressed() {
        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
        super.onBackPressed();
    }

    protected void bet() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", getBetCode());
            params.put("lotteryType", getLotteryId());
            params.put("phase", getPeriod());
            params.put("amount", getAmount());
            params.put("multiple", getBeishu());
            params.put("oneAmount", getOneAmount() * 100);
            params.put("prizeOptimize", isPrizeOptimize());//prizeOptimize奖金优化（优化：1；普通：0）
            params.put("codeFilter", "0");//codeFilter旋转过滤（过滤：1；普通：0）
            params.put("userCouponId", "" + couponId);//优惠劵Id，非优惠劵投注可以不写
            params.put("expectedPrize", expectedPrize);// 预计奖金
            if (App.isBaskOrder) {  // 晒单投注&& recommendType != 1
                params.put("way", recommendType);   // 0推荐、1不推荐、2保密
                params.put("proportions", proportions);
                params.put("proportionType", proportionType);
                params.put("isShowAmt", isShowAmt);
                params.put("isShowMaxSP", isShowMaxSP);
                httpPostJson(CommandUtil.USER_COMMON_BETTING, Commands.RECOMMENDEDORDERBET, params, true);
            } else {    // 普通投注
                httpPostJson(CommandUtil.USER_COMMON_BETTING, Commands.BET, params, true);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public long getAmount() {
        return getOneAmount() * getBeishu() * 100 * getZhushu();
    }

    public String isPrizeOptimize() {
        return "0";
    }

    public boolean recommendeble() {
        return false;
    }

    public String getPeriod() {
        return AppLotteryInfos.getPeriod(lotteryId);
    }

    /**
     * 根据lotteryId查询优惠劵
     */
    private void getCoupon() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", lotteryId);
            httpPostJson(CommandUtil.FINDUSERLOTTERYTYPECOUPON, Commands
                    .FINDUSERLOTTERYTYPECOUPON, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付联网——追号投注
     * betcode	string	投注内容
     * lotteryType	int	彩种
     * chaseType	int	追号类型 1:中奖停止 2:达到中奖彩金截止 3:正常截止
     * beginPhase	string	开始期
     * amt	string	单倍彩金
     * num	string	投注总期数
     * totalPrize	int	中奖总彩金 chaseType=2时使用
     * multiple	int	倍数
     * addition	int	大乐透是否追加 1是0否
     * advancedChase	string	高级追号
     */
    public void zhuihao() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", getBetCode());
            params.put("lotteryType", getLotteryId());
            params.put("beginPhase", getPeriod());
            if (isPrizeStop) {
                params.put("chaseType", 1);
            } else {
                params.put("chaseType", 3);
            }
            if (isZhuijia) {
                params.put("addition", 1);
            } else {
                params.put("addition", 0);
            }
            params.put("amt", getOneAmount() * getZhushu() * 100);
            params.put("num", getZhuiQi());
            params.put("multiple", getBeishu());
            params.put("totalPrize", "");
            httpPostJson(CommandUtil.CHASEBET, Commands.CHASEBET, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public int getLotteryId() {
        return lotteryId;
    }

    /**
     * 清空
     */
    protected abstract void clear();

    /**
     * 刷新列表
     */
    protected abstract void adapterChange();

    /**
     * 获取注数
     */
    public abstract int getZhushu();

    /**
     * 单注彩金(米)
     *
     * @return
     */
    public abstract int getOneAmount();

    /**
     * 投注彩金(米)
     *
     * @return
     */
    public long getMoney() {
        if (!beiShus.equals("") && beiShus.contains(",")) {
            long money = getBeishu() * getZhushu() * getOneAmount();
            String[] beis = beiShus.split(",");
            for (int i = 1; i < beis.length; i++) {
                int b = 1;
                try {
                    b = Integer.parseInt(beis[i]);
                } catch (Exception e) {
                    LogUtil.e(e.getMessage());
                }
                money = money + b * getZhushu() * getOneAmount();
            }
            return money;
        } else {
            return getBeishu() * getZhushu() * getOneAmount() * getZhuiQi();
        }
    }

    /**
     * 单倍彩金(米)
     *
     * @return
     */
    public int getAmt() {
        return getZhushu() * getOneAmount();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        // 顶部
        top_title = (TextView) findViewById(R.id.zhifu_top_title);
        top_hemai = (TextView) findViewById(R.id.zhifu_top_hemai);
        po_instruction = (TextView) findViewById(R.id.po_instruction);
        top_back = (ImageView) findViewById(R.id.zhifu_top_back);
        zhifu_top_rl = (RelativeLayout) findViewById(R.id.zhifu_top_rl);
        initTopLayout(zhifu_top_rl);
        if (AppLotteryInfos.isGaoPin(lotteryId)) {
            top_hemai.setVisibility(View.GONE);
        }

        // 中间
        center_ll = (LinearLayout) findViewById(R.id.zhifu_center_ll);

        // 底部
        btm_zhu = (TextView) findViewById(R.id.zhifu_bottom_tv_zhushu);
        btm_bei = (TextView) findViewById(R.id.zhifu_bottom_tv_bei);
        btm_money = (TextView) findViewById(R.id.zhifu_bottom_tv_money);
        btm_leftMoney = (TextView) findViewById(R.id.zhifu_bottom_tv_yue);
        btm_sure = (TextView) findViewById(R.id.zhifu_bottom_tv_zhifu);
        btm_clear = (TextView) findViewById(R.id.zhifu_bottom_tv_clear);
        btm_bask = (TextView) findViewById(R.id.zhifu_bottom_tv_start_bask);

        btm_bask.setVisibility(isShowStartBask() ? View.VISIBLE : View.GONE);
        if (App.isBaskOrder) {
            btm_bask.setVisibility(View.GONE);
            btm_sure.setText("购彩\n并晒单");
        }
        // 事件
        top_back.setOnClickListener(this);
        top_hemai.setOnClickListener(this);
        po_instruction.setOnClickListener(this);
        btm_sure.setOnClickListener(this);
        btm_clear.setOnClickListener(this);
        btm_bask.setOnClickListener(this);
    }

    /**
     * android4.4 及以上沉浸式布局
     */
    private void initTopLayout(ViewGroup topLayout) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            ViewGroup.LayoutParams params = topLayout.getLayoutParams();
//            params.height = Utils.dip2px(75);
//            topLayout.setLayoutParams(params);
//            topLayout.setPadding(0, Utils.dip2px(25), 0, 0);
        }
    }

    /**
     * 设置底部值
     */
    public void setBtmView() {
        String infoStr = getString(R.string.zhifu_leftmoney) + "<font color='#fd4a4a'>"
                + MySharedPreferences.getInstance().getBalance() + "</font>米";
        btm_leftMoney.setText(Html.fromHtml(infoStr));
        btm_zhu.setText(getZhushu() + "注");
        if (!isGaoJiZhuiHao) {
            btm_bei.setText(getBeishu() + "倍");
        } else {
            btm_bei.setText("追" + zhuiQi_GaoJi + "期");
        }
        btm_money.setText(Html.fromHtml("<font color='#fd4a4a'>" + getMoney() + "</font>米"));
        if (getZhuiQi() == 1 && couponZhifuView.couponListInfos.size() > 0) {
            couponZhifuView.setVisibility(View.VISIBLE);
            couponZhifuView.setMoney(getMoney());
        } else {
            couponZhifuView.setVisibility(View.GONE);
        }
    }

    public int getBeishu() {
        return beishu;
    }

    public String getMemo() {
        return getString(R.string.bask_memo_default);
    }

    public int getZhuiQi() {
        return zhuiQi;
    }

    public String getBetCode() {
        return "";
    }

    public void setTitleStr() {
        if (App.isBaskOrder) {
            top_title.setText("方案确认");
        } else {
            top_title.setText(AppLotteryInfos.getLotteryName(lotteryId) + "支付");
        }
    }

    /**
     * 是否显示发起晒单
     *
     * @return
     */
    public boolean isShowStartBask() {
        return false;
    }

    /**
     * 添加中间部分
     */
    protected void addCenter() {
        center_ll.addView(initCenterView());
    }

    protected abstract View initCenterView();

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        super.onClick(v);
        switch (v.getId()) {
            case R.id.zhifu_top_back:
                onBackPressed();
                break;
            case R.id.zhifu_top_hemai:
                onTopRightClick();
                break;
            case R.id.zhifu_bottom_tv_zhifu:
                if (App.isBaskOrder) {
                    if (recommendeble()) {
                        zhifuAction();
                    }
                } else {
                    zhifuAction();
                }
                break;
            case R.id.zhifu_bottom_tv_start_bask://发起晒单
                if (!App.isBaskOrder) {
                    shaidanAction();
                }
                break;
            case R.id.zhifu_bottom_tv_clear:
                showClearDialog();
                break;
        }
    }

    public void onTopRightClick() {
        if (hemaiAble()) {
            if (!MySharedPreferences.getInstance().getLoginStatus()) {
                AppLotteryInfos.clear();
                ViewCallBack.getInstance().countDownObjs.clear();
                ActivityTaskManager.getInstance().closeAllActivity();
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            } else {
                toHeMai();
            }
        }
    }

    /**
     * 可以发起合买的情况
     *
     * @return
     */
    protected boolean hemaiAble() {
        return true;
    }

    public boolean isJC() {
        return false;
    }

    private boolean isMoreMoney;
    private long lowMoney = 0;    // 投注差额

    private void zhifuAction() {
        if (MySharedPreferences.getInstance().getLoginStatus()) {
            if (getZhushu() == 0) {
                lingAlert();
            } else {
                if (!isAgree) {
                    new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("请阅读并同意" + getString(R.string.pay_o2o_xieyi))
                            .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }

                            }).setCancelable(false).create().show();
                    return;
                }

//                if (getMoney() < MIN_TOUZHU) {
//                    if (minTouZhuAlertDialog == null) {
//                        minTouZhuAlertDialog = new AlertDialog.Builder(this)
//                                .setMessage("投注彩金不能少于" + MIN_TOUZHU + "米")
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.cancel();
//                            }
//                        }).create();
//                    }
//                    minTouZhuAlertDialog.show();
//                    return;
//                }

                UMengTongJi_eventIds.BuyOnClick(this, "认购", "" + lotteryId, AppLotteryInfos.getLotteryName(lotteryId));
                if (!isJC() && getPeriod().equals("")) {// 竞彩无需判断期号
                    AppToast.getToast().show("未获取到期号不能进行投注！");
                    return;
                } else {
                    double leftMoney = Double.parseDouble(MySharedPreferences.getInstance().getBalance());
                    lowMoney = getMoney() - (long) leftMoney;
                    isMoreMoney = betAble(leftMoney);
                    int phases = getZhuiQi();

                    if (App.isBaskOrder && TextUtils.isEmpty(getMemo())) {
                        showToast("请输入晒单宣言");
                        return;
                    }

                    if (App.isBaskOrder && (proportions == -1 || proportionType == -1 || recommendType == -1 || isShowAmt == -1 || isShowMaxSP == -1)) {
                        showToast("请选择您的晒单方式");
                        return;
                    }
                    if (phases > 0) {
                        Log.e("fjlBetCode","getBetCode()");
                        Intent intent = new Intent(getContext(), PaymentActivity.class);
                        intent.putExtra("betCode", getBetCode());
                        intent.putExtra("lotteryId", getLotteryId());
                        intent.putExtra("phases", phases);
                        intent.putExtra("isMoreMoney", isMoreMoney);
                        intent.putExtra("needMoney", getMoney());
                        intent.putExtra("amount", getAmount());
                        intent.putExtra("multiple", getBeishu());
                        intent.putExtra("oneAmount", getOneAmount() * 100);
                        intent.putExtra("prizeOptimize", isPrizeOptimize());
                        intent.putExtra("couponId", couponId);
                        intent.putExtra("expectedPrize", expectedPrize);
                        intent.putExtra("recommendType", recommendType);
                        intent.putExtra("proportions", proportions);
                        intent.putExtra("proportionType", proportionType);
                        intent.putExtra("isShowAmt", isShowAmt);
                        intent.putExtra("isShowMaxSP", isShowMaxSP);
                        intent.putExtra("isPrizeStop", isPrizeStop);
                        intent.putExtra("isZhuijia", isZhuijia);
                        intent.putExtra("amt", (long) (getOneAmount() * getZhushu() * 100));
                        intent.putExtra("memo", getMemo());
                        startActivityForResult(intent, 100);
//                        showPayDialog();
                    }
                }
            }
        } else {
            AppLotteryInfos.clear();
            ViewCallBack.getInstance().countDownObjs.clear();
            ActivityTaskManager.getInstance().closeAllActivity();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        }
    }

    private void shaidanAction() {
        if (MySharedPreferences.getInstance().getLoginStatus()) {
            if (getZhushu() == 0) {
                lingAlert();
            } else {
                if (!isAgree) {
                    new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("请阅读并同意" + getString(R.string.pay_o2o_xieyi))
                            .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }

                            }).setCancelable(false).create().show();
                    return;
                }

                UMengTongJi_eventIds.BuyOnClick(this, "认购", "" + lotteryId, AppLotteryInfos.getLotteryName(lotteryId));
                if (!isJC() && getPeriod().equals("")) {// 竞彩无需判断期号
                    AppToast.getToast().show("未获取到期号不能进行投注！");
                    return;
                } else {
                    double leftMoney = Double.parseDouble(MySharedPreferences.getInstance().getBalance());
                    lowMoney = getMoney() - (long) leftMoney;
                    isMoreMoney = betAble(leftMoney);
                    int phases = getZhuiQi();

                    if (phases > 0) {
                        Intent intent = new Intent(getContext(), ShaiDanPayActivity.class);
                        intent.putExtra("betCode", getBetCode());
                        intent.putExtra("lotteryId", getLotteryId());
                        intent.putExtra("phases", phases);
                        intent.putExtra("isMoreMoney", isMoreMoney);
                        intent.putExtra("needMoney", getMoney());
                        intent.putExtra("amount", getAmount());
                        intent.putExtra("multiple", getBeishu());
                        intent.putExtra("oneAmount", getOneAmount() * 100);
                        intent.putExtra("prizeOptimize", isPrizeOptimize());
                        intent.putExtra("couponId", couponId);
                        intent.putExtra("expectedPrize", expectedPrize);
                        intent.putExtra("recommendType", recommendType);
                        intent.putExtra("proportions", proportions);
                        intent.putExtra("proportionType", proportionType);
                        intent.putExtra("isShowAmt", isShowAmt);
                        intent.putExtra("isShowMaxSP", isShowMaxSP);
                        intent.putExtra("isPrizeStop", isPrizeStop);
                        intent.putExtra("isZhuijia", isZhuijia);
                        intent.putExtra("zhuShu", getZhushu());
                        intent.putExtra("amt", (long) (getOneAmount() * getZhushu() * 100));
                        intent.putExtra("memo", getMemo());
                        startActivityForResult(intent, 100);
                    }
                }
            }
        } else {
            AppLotteryInfos.clear();
            ViewCallBack.getInstance().countDownObjs.clear();
            ActivityTaskManager.getInstance().closeAllActivity();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        }
    }

    public void goBet() {
        bet();
    }

    public boolean betAble(double leftMoney) {
        return leftMoney >= getMoney();
    }

    public void lingAlert() {
        AppToast.getToast().show(R.string.touyizhu);
    }


    private AlertDialog togetherBuyMinAlertDialog = null;
    private AlertDialog minTouZhuAlertDialog = null;

    /**
     * 发起合买
     */
    private void toHeMai() {
        if (getMoney() < MIN_HEMAI) {
            if (togetherBuyMinAlertDialog == null) {
                togetherBuyMinAlertDialog = new AlertDialog.Builder(this).setMessage("合买最少彩金为" +
                        MIN_HEMAI + "米").setPositiveButton("确定", new DialogInterface
                        .OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create();
            }
            togetherBuyMinAlertDialog.show();
        } else if (zhuiQi > 1) {
            AppToast.getToast().show("合买不支持追号");
        } else {
            Intent intent = new Intent(getContext(), HeMaiFaQiActivity.class);
            intent.putExtra(IntentParamUtils.BETCODE, getBetCode() + "");
            intent.putExtra(IntentParamUtils.LOTTERYID, lotteryId + "");
            intent.putExtra(IntentParamUtils.PERIOD, getPeriod());
            intent.putExtra(IntentParamUtils.MONEY, getMoney());
            intent.putExtra(IntentParamUtils.ONEAMOUNT, getOneAmount());
            intent.putExtra(IntentParamUtils.AMT, getAmt());
            intent.putExtra(IntentParamUtils.MULTIPLE, getBeishu());
            intent.putExtra(IntentParamUtils.EXPECTEDPRIZE, expectedPrize);
            double leftMoney = 0;
            try {
                leftMoney = Double.parseDouble(MySharedPreferences.getInstance().getBalance().toString());
            } catch (Exception e) {
                LogUtil.e(e.getMessage());
            }
            intent.putExtra(IntentParamUtils.LEFTMONEY, leftMoney);
            startActivityForResult(intent, IntentParamUtils.SEND_TOGETHERBUY);
        }
    }

    public void findUserAccount() {
        JSONObject request_json = new JSONObject();
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, request_json, true);
    }

    /**
     * 显示是否支付对话框
     */
    public void showPayDialog() {
        if (payDialog == null) {
            payDialog = new AlertDialog.Builder(this).setTitle("温馨提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            goBet();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        payDialog.setMessage("确认购买，立即支付");
        payDialog.show();
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        DJ_ProgressDialog.dissmiss();
        switch (requestCode) {
            case CommandUtil.USER_COMMON_BETTING:
                if (App.isBaskOrder) { // && recommendType != 1
                    showOkDialog();
                    break;
                }
            case CommandUtil.CHASEBET:
                if (resultBean.getErrorcode().equals("0")) {
                    orderId = JSON.parseObject(resultBean.getData(), BetResponse
                            .class).getOrderid();
                    if (isMoreMoney) {
                        buyOk(orderId, "投注成功");
                    } else {
                        Intent intent = new Intent(getContext(), RechargeActivity.class);
                        intent.putExtra(IntentParamUtils.ORDER_ID, orderId);
                        intent.putExtra(IntentParamUtils.lowMoney, lowMoney);
                        startActivityForResult(intent, IntentParamUtils.LOWMONEY_TO_RECHARGE_OK);
                    }
                } else {
                    showToast(resultBean.getMsg());
                }
                break;
            case CommandUtil.ACCOUNT_MONEY:
                AccountMoneyResponse accountMoneyResponse = JSON.parseObject(resultBean.getData()
                        , AccountMoneyResponse.class);
                MySharedPreferences.getInstance().setBalance(PublicMethod.formatBalance
                        (accountMoneyResponse.getBalance()));
                setBtmView();

                break;
            case CommandUtil.FINDUSERLOTTERYTYPECOUPON:
                CouponListByLotteryBean bean = JSON.parseObject(result, CouponListByLotteryBean
                        .class);
                if (bean.getData().size() > 0) {
                    couponZhifuView.setList(bean.getData());
                } else {
                    couponZhifuView.setVisibility(View.GONE);
                }
                break;
        }

    }

    /**
     * 投注成功
     *
     * @param orderId
     */
    private void buyOk(final String orderId, String tishi) {
        final String lotteryType = lotteryId + "";
        MySharedPreferences.getInstance().setBetCodeBean(lotteryId, new ArrayList<>());
        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage(tishi)
                .setPositiveButton("查看订单", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        clear();
                        Intent intent;
                        if (lotteryType.contains("30") || lotteryType.contains("50")) {
                            intent = new Intent(getContext(), JCOrderDetailActivity.class);
                        } else if (lotteryType.contains("40")) {
                            intent = new Intent(getContext(), OldFootballOrderDetailActivity.class);
                        } else {
                            intent = new Intent(getContext(), NumLotteryOrderDetailActivity.class);

                        }
                        intent.putExtra(IntentParamUtils.BETDETAILID, orderId);
                        getContext().startActivity(intent);
                        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
                        setResult(0x6);
                        BetBaseActivity.this.finish();
                    }
                })
                .setNegativeButton("完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clear();
                        dialog.cancel();
                        setResult(0x6);
                        AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
                        BetBaseActivity.this.finish();
                    }
                }).setCancelable(false).create().show();
    }

    @Override
    protected void onFailure(int requestCode, String errorcode, String message) {
        if (requestCode == CommandUtil.FINDUSERLOTTERYTYPECOUPON) {
            if (errorcode.equals("900003")) {
                // 数据为空
                couponZhifuView.setVisibility(View.GONE);
            } else {    // 联网失败
                couponZhifuView.setVisibility(View.VISIBLE);
                couponZhifuView.netError();
                couponZhifuView.setOnRefreshData(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getCoupon();
                    }
                });
            }
        } else {
            showToast(message);
        }
    }

    /**
     * 清除对话框
     */
    private void showClearDialog() {

        if (clearDialog == null) {
            clearDialog = new SureDialog(this, new OnDialogOKCancleClickListener() {

                @Override
                public void onOKClick() {
                    clear();
                    changCi = 0;
                    zhushu = 0;
                    adapterChange();
                    setBtmView();
                    clearDialog.dismiss();
//                    AppLotteryCodeListManager.betType = AppLotteryCodeListManager.FIRSTENTER;
//                    finish();
                }

                @Override
                public void onCancleClick() {
                    // TODO Auto-generated method stub
                    clearDialog.dismiss();
                }
            }, "", "确定要清除所有投注吗？", "确定", "取消");
        }
        clearDialog.show();
    }

    /**
     * 时间截止提示对话框
     */
    public void showEndTimeDialog(String period, String periodNew) {
        AppLotteryInfos.period_buffer.append(period + lotteryId);
        try {
            if (endTimeDialog == null) {
                OnDialogOKCancleClickListener clickListener = new OnDialogOKCancleClickListener() {

                    @Override
                    public void onOKClick() {
                        endTimeDialog.dismiss();
                    }

                    @Override
                    public void onCancleClick() {
                        // TODO Auto-generated method stub
                        endTimeDialog.dismiss();
                    }
                };

                if (periodNew.equals("")) {
                    endTimeDialog = new SureDialog(this, clickListener, "", "第" + period +
                            "期已截止！", "确定", "");
                } else {
                    endTimeDialog = new SureDialog(this, clickListener, "", "正在获取新期...", "确定", "");
                }
            }

            endTimeDialog.show();
        } catch (Exception e) {
            L.i(TAG, e.getMessage());
        }
    }

    @Override
    public void checkCoupon(long couponMoney, String couponId) {
        this.couponMoney = couponMoney;
        this.couponId = couponId;
        if (couponMoney == 0) {
            btm_money.setText(Html.fromHtml("<font color='#fd4a4a'>" + getMoney() + "</font>米"));
        } else {
            String payInfor = "优惠<font color='#fd4a4a'>" + couponMoney +
                    "</font>米，实付<font color='#fd4a4a'>" +
                    (getMoney() - couponMoney) + "</font>米";
            btm_money.setText(Html.fromHtml(payInfor));
        }
    }

    private Dialog okDialog;    // 晒单成功

    private void showOkDialog() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_recommend_ok,
                null);
        TextView btn1 = contentView.findViewById(R.id.rrok_dialog_btn1);
        TextView btn2 = contentView.findViewById(R.id.rrok_dialog_btn2);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                okDialog.cancel();
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                okDialog.cancel();
                Intent intent = new Intent(getContext(), MyRecommendOrderActivity.class);
                startActivity(intent);
            }
        });
        if (okDialog == null) {
            okDialog = new AppCompatDialog(getContext());
        }
        okDialog.setContentView(contentView);
        okDialog.setCanceledOnTouchOutside(false);
        okDialog.show();
        okDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                clear();
                AppLotteryCodeListManager.betType = AppLotteryCodeListManager.OKTOBACK;
                setResult(0x06);
                finish();

            }
        });
        okDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                okDialog.dismiss();
            }
        });
    }

    protected boolean isAgree = true;
    private AlertDialog xieYiDialog = null;

    /**
     * 支付列表底部控件( 支付协议 )
     *
     * @return
     */
    protected View getListFooterView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_payfooterview, null);
        final CheckBox checkBox = view.findViewById(R.id.pay_footer_checkbox);
        TextView xieYi_tv = view.findViewById(R.id.pay_footer_xieyi_tv);
        checkBox.setChecked(isAgree);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = isChecked;
            }
        });
        xieYi_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xieYiDialog == null) {
                    View view = View.inflate(getContext(), R.layout.zhuce_xieyi, null);
                    TextView neiRong = view.findViewById(R.id.dialog_neirong);
                    InputStream inputStream = getResources().openRawResource(R.raw.xieyi);
                    neiRong.setText(PublicMethod.getStringFromStream(inputStream));

                    xieYiDialog = new AlertDialog.Builder(getContext()).setView
                            (view).setTitle(R.string.protocol).setPositiveButton("同意", new
                            DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    checkBox.setChecked(true);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).create();

                }

                xieYiDialog.show();
            }
        });
        return view;
    }

}
